#include <signal.h>
#include <vector>
#include <iostream>

#include <workflow/WFFacilities.h>
#include <workflow/MySQLMessage.h>
#include <workflow/MySQLResult.h>

using namespace std;

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    cout << "sighandler is processing" << endl;
    waitGroup.done();
}

void mysqlCallback(WFMySQLTask * mysqlTask)
{
    using namespace protocol;
    cout << "mysqlTask is running" << endl;
    //错误检测
    int state = mysqlTask->get_state();
    int error = mysqlTask->get_error();
    if(state != WFT_STATE_SUCCESS){
        printf("error: %s\n", WFGlobal::get_error_string(state, error));
        return;
    }       
    
    //检测sql语句的语法错误
    auto resp = mysqlTask->get_resp();
    if(resp->get_packet_type() == MYSQL_PACKET_ERROR) {
        printf("error code %d, %s\n", resp->get_error_code(),
               resp->get_error_msg().c_str());
        return ;
    }

    MySQLResultCursor cursor(resp);
    if(cursor.get_cursor_status() == MYSQL_STATUS_OK) {
        //处理写操作
        printf("OK. %llu rows affected. %d warnings. insert id is %llu\n",
            cursor.get_affected_rows(),
            cursor.get_warnings(),
            cursor.get_insert_id());
    } 
    else if(cursor.get_cursor_status() == MYSQL_STATUS_GET_RESULT)
    {   //处理读操作
        //先读取所有的字段信息
        const MySQLField * const * arr = cursor.fetch_fields();
        for(int i = 0; i < cursor.get_field_count(); ++i) {
            cout << "db = " << arr[i]->get_db() << ","
                 << "table = " << arr[i]->get_table() << "," 
                 << "name = " << arr[i]->get_name() << ","
                 << "type = " << datatype2str(arr[i]->get_data_type()) << endl;
        }

        //读取每一行的数据
        vector<vector<MySQLCell>> rows;
        cursor.fetch_all(rows);
        cout << "query set is " << rows.size() << " rows" << endl;
        for(auto & row : rows) {
            for(auto & cell : row) {
                if(cell.is_int()) {
                    cout << cell.as_int() << " ";
                } else if(cell.is_string()) {
                    cout << cell.as_string() << " ";
                } else if (cell.is_time()) {
                    cout << cell.as_time() << " ";
                } else if (cell.is_datetime()) {
                    cout << cell.as_datetime() << " ";
                }
            }
            cout << "\n";
        }
    }
}

void test0()
{
    signal(SIGINT, sighandler);
    //创建任务
    string mysqlurl = "mysql://root:1234@localhost:3306";
    auto mysqlTask = WFTaskFactory::create_mysql_task(mysqlurl, 0, mysqlCallback);
    //设置任务的属性
    auto req = mysqlTask->get_req();
    //string query("INSERT INTO cloudisk.tbl_user_token(user_name, user_token) values('Jackie', 'token_abcde')");
    string query("select * from cloudisk.tbl_user_token");
    req->set_query(query);
    //交给框架来运行
    mysqlTask->start();

    waitGroup.wait();
}


int main()
{
    test0();
    return 0;
}

